<?php
class App_Source_Media_Handler_Video extends App_Source_Media_Handler
{
	private $_fileObj;

	protected function InitFile()
	{
		$this->_fileObj = new ffmpeg_movie($this->_filePath);
		if (!$this->_fileObj || !$this->_fileObj->hasVideo() || !$this->_fileObj->getDuration())
		{
			$this->SetError(Mozg_Lang::_('VIDEO_STREAM_NOT_FOUND'));
		}

		$this->_fileMimeType = 'video/unknown';
		$this->_fileSize = filesize($this->_filePath);
		$this->_fileLength = $this->_fileObj->getDuration();
	}

	public function CreateThumbNail()
	{
		if (false === $this->_fileThumbNail)
		{
			$this->_fileThumbNail = '';

			$destPath = $this->GetDestPath();
			if (false === $destPath) return false;

			$frameCount = (int)$this->_fileObj->getFrameCount();
			if ($frameCount)
			{
				$frame = $this->_fileObj->getFrame(ceil(min($frameCount, 1000) / 2));
				if ($frame)
				{
					$image = $frame->toGDImage();
					if ($image)
					{
						$filename = pathinfo($this->_filePath, PATHINFO_FILENAME);
						$thumbPath = $destPath.$filename. '-thumb.jpg';
						@ImageJpeg($image, $thumbPath, 90);
						@ImageDestroy($image);

						if (is_file($thumbPath))
						{
							$this->_fileThumbNail = $thumbPath;
						}
					}
				}
			}
		}

		return $this->_fileThumbNail;
	}

	public function Convert($code)
	{
		$destPath = $this->GetDestPath();
		if (false === $destPath)
		{
			$this->SetConvertStatus(App_Source_Media_Status::HasError);
			$this->SetError(Mozg_Lang::_('ERROR_OCCURED_WHILE_PROCCESSING_FILE'));
			return false;
		}

		$fileInfo = pathinfo($this->GetFilePath());
		$destFile = $destPath.$fileInfo['filename']. '.flv';
		$newSize = implode('x', $this->GetNewSize($this->_fileObj->getFrameWidth(), $this->_fileObj->getFrameHeight()));

		$command = 'ffmpeg -y -i %1$s -acodec libmp3lame -s ' .$newSize. ' -ar 44100 -vcodec flv %2$s';
		$result = $this->RunShellCommand($command, $destFile, $code);
		if (!$result)
		{
			$this->SetConvertStatus(App_Source_Media_Status::HasError);
			$this->SetError(Mozg_Lang::_('ERROR_OCCURED_WHILE_PROCCESSING_FILE'));
			return false;
		}

		$this->_fileMimeType = 'video/x-flv';
		$this->SetConvertStatus(App_Source_Media_Status::NotProcessed);

		return $destFile;
	}

	private function GetNewSize($width, $height)
	{
		list($maxWidth, $maxHeight) = Mozg_Cfg::Get('global/media')->GetVideoSizeTo();

		$diffX = max($width - $maxWidth, 0);
		$diffY = max($height - $maxHeight, 0);
		if ($diffX < $diffY)
		{
			$tnHeight = $height - $diffY;

			$ratio = $tnHeight/$height;
			$tnWidth = ceil($ratio*$width);
		}
		else
		{
			$tnWidth = $width - $diffX;

			$ratio = $tnWidth/$width;
			$tnHeight = ceil($ratio*$height);
		}

		return array($tnWidth, $tnHeight);
	}
}